/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.fanli.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.DialogUtil;
import com.mol.market.common.util.DialogUtil.YesNoDialogListener;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.AppListAdapter.ViewBinder;
import com.mol.market.common.widget.LazyloadListActivity;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 兑换界面.
 *
 * @author Chaos
 * @date 2012-07-25
 * @since Version 0.9.5
 */
public class ExchangeSelectActivityOther extends LazyloadListActivity implements
    OnClickListener, ApiRequestListener, Observer {

  /**
   * View的State
   */
  private static final int VIEW_EXCHANGE_RECORD = Constants.ID_EXCHANGE_RECORD;
  private static final int VIEW_EXCHANGE_INCOME = Constants.ID_EXCHANGE_INCOME;


  private AppListAdapter mAdapter;
  private FrameLayout    mLoading;
  private ProgressBar    mProgress;
  private TextView       mNoData;
  private RelativeLayout mGoMakeMoney;
  private Button         mGo;

  private int    mTotalSize = 0;
  private int    mCurId     = -1;

  private String mTitle     = null;


  @Override
  public boolean doInitView(Bundle savedInstanceState) {

    setContentView(R.layout.activity_exchange);

    Intent intent = getIntent();

    mCurId = intent.getIntExtra(ExchangeActivityOther.INTENT_EXTRA_ID, -1);
    mTitle = intent.getStringExtra(ExchangeActivityOther.INTENT_EXTRA_TITLE);

    if (mCurId == -1) {
      return false;
    }

    mSession.cashbackManager.addObserver(this);

    initTopBar(mCurId);

    initView(mCurId);

    lazyload();

    return true;
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    mSession.cashbackManager.deleteObserver(this);
    mAdapter.recycle();
    mAdapter = null;
  }

  @Override
  public void doLazyload() {

    switch (mCurId) {
      case VIEW_EXCHANGE_RECORD:
        // 兑换记录
        MarketAPI.getExchangeDetail(this, this,
            getStartIndex(), getItemsPerPage());
        break;
      case VIEW_EXCHANGE_INCOME:
        // 收入详细
        MarketAPI.getExchangeReward(this, this,
            getStartIndex(), getItemsPerPage());
        break;
      default:
        MarketAPI.getExchangeGoods(this, this, mCurId);
        break;
    }
  }


  @Override
  public AppListAdapter doInitListAdapter() {
    switch (mCurId) {
      case VIEW_EXCHANGE_RECORD:

        mAdapter = AdapterFactory.buildAdapter(this, AdapterFactory.TYPE_EX);
        mAdapter.setLazyloadListener(this);
        break;
      case VIEW_EXCHANGE_INCOME:

        mAdapter = AdapterFactory.buildAdapter(this, AdapterFactory.TYPE_IN);
        mAdapter.setLazyloadListener(this);
        break;
      default:

        mAdapter = AdapterFactory.buildAdapter(this, AdapterFactory.TYPE_GOODS);
        break;
    }
    mAdapter.setActivity(this);
    return mAdapter;
  }

  @Override
  protected int getItemCount() {
    return mTotalSize;
  }

  /**
   * 初始化TopBar
   * -------------------------
   * | title             任务 |
   * -------------------------
   *
   * @param whichView
   */
  private void initTopBar(final int whichView) {
    TopBar.createTopBar(mSession,
        this,
        new View[] {
            findViewById(R.id.top_bar_title),
            findViewById(R.id.top_bar_tv_money),
            findViewById(R.id.top_bar_btn_exchange) },
        new int[] {
            View.VISIBLE,
            View.VISIBLE,
            View.VISIBLE },
        getTitleByView(whichView),
        getString(R.string.button_text));
    // add listener
    findViewById(R.id.top_bar_btn_exchange).setOnClickListener(this);
  }

  private void initView(int whichView) {
    mList = (ListView) findViewById(android.R.id.list);
    mLoading = (FrameLayout) findViewById(R.id.loading);
    mProgress = (ProgressBar) findViewById(R.id.progressbar);
    mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
    mProgress.setVisibility(View.VISIBLE);
    mGoMakeMoney = (RelativeLayout) findViewById(R.id.rl_gomakemoney);
    mGo = (Button) findViewById(R.id.btn_go);
    mGo.setOnClickListener(this);
    mNoData = (TextView) findViewById(R.id.no_data);
    mNoData.setOnClickListener(this);
    if (whichView == VIEW_EXCHANGE_INCOME || whichView == VIEW_EXCHANGE_RECORD) {
      mList.setEmptyView(mGoMakeMoney);
    } else {
      mList.setEmptyView(mLoading);
    }
  }

  /**
   * 不同页面返回不同的title
   *
   * @param whichView
   * @return
   */

  private String getTitleByView(final int whichView) {
    switch (whichView) {
      case VIEW_EXCHANGE_RECORD:
        //兑换记录
        return getString(R.string.exchange_h);
      case VIEW_EXCHANGE_INCOME:
        //收入明细
        return getString(R.string.exchange_d);
      default:
        return mTitle;
    }
  }

  @Override
  public void onClick(View v) {
    if (v.getId() == R.id.top_bar_btn_exchange || v.getId() == R.id.btn_go) {
      Intent i = new Intent(getApplicationContext(), MakeMoneyActivity.class);
      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(i);
    } else {
      // 重试
      mNoData.setVisibility(View.GONE);
      mProgress.setVisibility(View.VISIBLE);
      lazyload();
    }
  }

  /**
   * 预处理返利任务列表数据
   */
  @SuppressWarnings("unchecked")
  private void handleContent(HashMap<String, Object> obj) {

    if (mTotalSize <= 0) {
      // 获取总大小
      mTotalSize = (Integer) obj.get(Constants.KEY_TOTAL_SIZE);
    }

    mAdapter.addDataList(
            (ArrayList<HashMap<String, Object>>) obj.get(Constants.KEY_TASK_LIST));
    setLoadResult(true);
  }

  @SuppressWarnings("unchecked")
  @Override
  public void onSuccess(int method, Object obj) {
    switch (method) {
      case MarketAPI.ACTION_GET_EXCHANGE_GOODS:
        mAdapter.addDataList((ArrayList<HashMap<String, Object>>) obj);
        setLoadResult(true);
        break;
      case MarketAPI.ACTION_GET_EXCHANGE_REWARD:
        // 收入明细
      case MarketAPI.ACTION_GET_EXCHANGE_DETAIL:
        // 兑换明细
        handleContent((HashMap<String, Object>) obj);
        mLoading.setVisibility(View.GONE);
        break;
      default:
        break;
    }
  }

  @Override
  public void onError(int method, int statusCode) {

    switch (method) {

      case MarketAPI.ACTION_GET_EXCHANGE_REWARD:
        // 收入明细
      case MarketAPI.ACTION_GET_EXCHANGE_DETAIL:
        // 兑换明细
        if (statusCode == ApiAsyncTask.BUSINESS_ERROR) {
          // 没有对应数据, 返回任务列表页让用户参与赚钱任务
          mProgress.setVisibility(View.GONE);
          mGo.setVisibility(View.VISIBLE);
        } else {
          mNoData.setVisibility(View.VISIBLE);
          mNoData.setText(getString(R.string.no_data));
          mProgress.setVisibility(View.GONE);
        }
        setLoadResult(false);
        break;
      default:
        mNoData.setVisibility(View.VISIBLE);
        mNoData.setText(getString(R.string.no_data));
        mProgress.setVisibility(View.GONE);
        setLoadResult(false);
        break;
    }
  }

  @Override
  public void update(Observable observable, Object data) {

    if (data instanceof Boolean) {

      if ((Boolean) data) {
        // 查看兑换结果详情
        DialogUtil.createConfirmResultDialog(this, 2,
            getString(R.string.exchange_success),
            new DialogUtil.WarningDialogListener() {

              @Override
              public void onWarningDialogOK(int id) {
                Utils.jumpToPage(
                    ExchangeSelectActivityOther.this,
                    ExchangeSelectActivityOther.class,
                    false,
                    new String[] {
                        ExchangeActivityOther.INTENT_EXTRA_ID,
                        ExchangeActivityOther.INTENT_EXTRA_TITLE },
                    new Serializable[] {
                        Constants.ID_EXCHANGE_RECORD,
                        getString(R.string.exchange_h)
                    });
              }

              @Override
              public void onWarningDialogCancel(int id) {
                // do nothing
              }
            }).show();
      }

    }

  }

  /**
   * 适配器工厂
   */
  static class AdapterFactory {
    /**
     * 兑换物品
     */
    public static final int TYPE_GOODS = 0;
    /**
     * 兑换记录
     */
    public static final int TYPE_EX    = 1;
    /**
     * 收入明细
     */
    public static final int TYPE_IN    = 2;

    /**
     * 兑换按钮的状态值
     */
    private static final int BTN_EXCHANGE_OK      = 0;
    private static final int BTN_EXCHANGE_NO_MONEY = 1;
    private static final int BTN_EXCHANGE_NO_GOODS = 2;

    /**
     * 获取适配器
     *
     * @param type 适配器类型Code
     * @return 对应的适配器，主要响应不同的布局文件
     */

    public static AppListAdapter buildAdapter(Activity context, int type) {

      switch (type) {
        case TYPE_GOODS:

          return buildGoodsAdapter(context);

        case TYPE_EX:

          return buildEXAdapter(context);

        case TYPE_IN:

          return buildINAdapter(context);

        default:
          return null;
      }
    }

    /**
     * 生成兑换物品列表适配器<br>
     * Ex. Q币，移动充值卡 etc.
     */

    private static AppListAdapter buildGoodsAdapter(final Activity context) {
      AppListAdapter adapter = new AppListAdapter(context,
          null,
          R.layout.fanli_item_exchange_qb,
          new String[] {
              Constants.KEY_ICON,
              Constants.KEY_PRODUCT_NAME,
              Constants.KEY_COST,
              Constants.KEY_STATUS },
          new int[] {
              R.id.iv_icon,
              R.id.tv_name,
              R.id.tv_money,
              R.id.ib_exchange });
      adapter.setViewBinder(new ViewBinder() {
        @SuppressWarnings("unchecked")
        @Override
        public boolean setViewValue(View view, Object data, int position,
            Object textRepresentation) {
          if (view.getId() == R.id.ib_exchange) {
            Button v = (Button) view;
            HashMap<String, Object> item = (HashMap<String, Object>) data;
            int state = Utils.getInt((String) textRepresentation);
            setButtonState(context, item, state, v);
            return true;
          }
          return false;
        }
      });
      return adapter;
    }

    /**
     * 给Button(兑换按钮)设置状态
     */
    private static void setButtonState(final Activity context,
        HashMap<String, Object> data, final int state, final Button v) {

      switch (state) {
        case BTN_EXCHANGE_OK:
          // 可兑换
          v.setBackgroundDrawable(context.getResources().getDrawable(
              R.drawable.selector_btn_bg_light));
          final String id = (String) data.get(Constants.KEY_ID);
          final String name = (String) data.get(Constants.KEY_PRODUCT_NAME);
          final String money = (String) data.get(Constants.KEY_COST);
          v.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              doExchangeConfirm(context, money, name, id);
            }
          });
          break;
        case BTN_EXCHANGE_NO_MONEY:
          // 余额不足
          v.setBackgroundDrawable(context.getResources().getDrawable(
              R.drawable.selector_btn_bg_dark));
          v.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              Utils.makeEventToast(context,
                  context.getString(R.string.exchange_error_3), false);
            }
          });
          break;
        case BTN_EXCHANGE_NO_GOODS:
          // 已售罄
          v.setBackgroundDrawable(context.getResources().getDrawable(
              R.drawable.btn_untouch));
          v.setText(context.getResources().getString(R.string.exchange_over));
          v.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              Utils.makeEventToast(context,
                  context.getString(R.string.exchange_error_4), false);
            }
          });
          break;
      }
    }

    /**
     * 兑换确认
     */
    private static void doExchangeConfirm(final Activity context,
        final String money, final String name, final String goods) {
      DialogUtil.createYesNoTitleDialog(
          context,
          1,
          name,
          context.getString(R.string.exchange_confirm, money),
          new YesNoDialogListener() {

            @Override
            public void onYesDialog(int id) {
              Session.get(context).cashbackManager.exchange(goods);
            }

            @Override
            public void onNoDialog(int id) {
              // no process
            }
          }).show();
    }

    /**
     * 生成兑换记录列表适配器
     */

    private static AppListAdapter buildEXAdapter(Activity context) {
      return new AppListAdapter(context,
          null,
          R.layout.fanli_item_exchange_record,
          new String[] {
              Constants.KEY_ICON,
              Constants.KEY_PRODUCT_NAME,
              Constants.KEY_INFORMATION,
              Constants.KEY_COST,
              Constants.KEY_EXCHANGE_TIME },
          new int[] {
              R.id.iv_icon,
              R.id.tv_name,
              R.id.tv_description,
              R.id.tv_getmoney,
              R.id.tv_time });
    }

    /**
     * 生成收入明细列表适配器
     */

    private static AppListAdapter buildINAdapter(Context context) {
      return new AppListAdapter(context,
          null,
          R.layout.fanli_item_exchange_income,
          new String[] {
              Constants.KEY_ICON,
              Constants.KEY_PAY,
              Constants.KEY_TYPE,
              Constants.KEY_STATUS,
              Constants.KEY_REWARD_TIME },
          new int[] {
              R.id.iv_icon,
              R.id.tv_getmoney,
              R.id.tv_description,
              R.id.tv_state,
              R.id.tv_time });
    }
  }

}
